package com.decent.ejfadmin.report.controller;

import com.decent.ejfadmin.common.bean.Page;
import com.decent.ejfadmin.report.service.CollectCardUserReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
 * @author weicx
 * @date 2018/08/01
 */
@RestController
@Slf4j
@RequestMapping("CollectCardUserReportController")
public class CollectCardUserReportController {
    @Autowired
    private CollectCardUserReportService collectCardUserReportService;

    /**
     * 收卡会员统计
     *
     * @param page        分页组件
     * @param startTime   查询开始时间
     * @param endTime     查询结束时间
     * @param userAccount 会员编号/名称
     * @param area        发行地区
     * @return Page
     */
    @RequestMapping("/collectCardUserReportPage")
    public Page collectCardUserReportPage(Page page, String startTime, String endTime, String userAccount, String area) {
        try {
            return collectCardUserReportService.collectCardUserReportPage(page, startTime, endTime, userAccount, area);
        } catch (Exception e) {
            log.warn("收卡会员统计异常:[{}]", e);
            page.setResultList(new ArrayList<>());
            page.setTotal(0);
            return page;
        }

    }

    /**
     * 收卡会员统计导出
     *
     * @param startTime   查询开始时间
     * @param endTime     查询结束时间
     * @param userAccount 会员编号/名称
     * @param area        发行地区
     * @return Page
     */
    @RequestMapping("downLoad")
    public void downLoad( String startTime, String endTime, String userAccount, String area, HttpServletResponse response) {
        ServletOutputStream writer = null;
        try {
            response.setCharacterEncoding("GBK");
            response.setContentType("text/html;charset=GBK");
            writer = response.getOutputStream();
            if (org.apache.commons.lang.StringUtils.isBlank(startTime) || org.apache.commons.lang.StringUtils.isBlank(endTime)) {
                String msg = "<script >alert('输入起始时间！');</script>";
                IOUtils.write(msg.getBytes("GBK"), writer);
                writer.flush();
                return;
            }
            collectCardUserReportService.downLoad( startTime, endTime, userAccount, area, response);
        } catch (Exception e) {
            log.warn("收卡会员统计导出出错[{}]", e);
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
}
